<?php
/**
 * File from WEBO Site InSight, WEBO Software (http://www.webogroup.com/)
 *
 **/

class SiteInSightWidgetAPI
{
	private $DB;
	private $widgetName;
	private static $mainPage = false;
	public $options;
	private $buffers = array();

	public function SiteInSightWidgetAPI($DB, $widgetName, $options, $getMainPage = true)
	{
		$this->DB = $DB;
		$this->widgetName = $widgetName;
		$this->options = $options;
		if (function_exists('curl_init') && $getMainPage && (self::$mainPage == false))
		{
			self::$mainPage = $this->loadPage('http://' . $_SERVER['HTTP_HOST'] . $this->options['siteURL']);
		}
	}

	public function storeWidgetSettings($settings)
	{
		return $this->DB->storeWidgetSettings($this->widgetName, $settings);
	}

	public function storeWidgetData($fields)
	{
		return $this->DB->storeWidgetData($this->widgetName, $fields);
	}

	public function getWidgetData($condition = array(), $orderField = 'date', $orderDirection = 0)
	{
		return $this->DB->getWidgetData($this->widgetName, $condition, $orderField, $orderDirection);
	}

	public function loadPage($url)
	{
		$url = strtolower($url);
		if (!function_exists('curl_init') || empty($url) || (substr($url, 0, 4) != 'http'))
		{
			return false;
		}
		$ch = curl_init($url);
		if (!$ch)
		{
			return false;
		}
		$this->buffers = array();
		curl_setopt($ch, CURLOPT_TIMEOUT, 15);
		curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'saveHeaders'));
		curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, 'saveBody'));
		if (curl_exec($ch))
		{
			$body = empty($this->buffers['body']) ? '' : $this->buffers['body'];
			$headers = empty($this->buffers['headers']) ? '' : $this->buffers['headers'];
			return array('headers' => $headers, 'body' => $body);
		}
		else
		{
			return false;
		}
	}

	private function writeData($string, $key)
	{
		$this->buffers[$key] .= $string;
		return strlen($string);
	}

	private function saveHeaders($ch, $string)
	{
		return $this->writeData($string, 'headers');
	}

	private function saveBody($ch, $string)
	{
		return $this->writeData($string, 'body');
	}

	public function getMainPage()
	{
		return self::$mainPage;
	}
}
